package ps.yj.y1j0.data.database;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * data manager
 *
 * @author yanjun
 */
public class YJDataManagerImpl implements YJDataManager {
    private static YJDataManagerImpl dataManager = null;
    private final YJDataSource dataSource;

    private YJDataManagerImpl() {
        dataSource = YJDataSource.getInstance();
    }

    public synchronized static YJDataManagerImpl getInstance() {
        if (dataManager == null)
            dataManager = new YJDataManagerImpl();
        return dataManager;
    }

    @Override
    public int updateTable(String sql, Object[] values) {
        int r = 0;
        if (values == null) return r;
        try {
            PreparedStatement statement = dataSource.createConnection().prepareStatement(sql);
            for (int i = 1; i <= values.length; i++) {
                statement.setObject(i, values[i - 1]);
            }
            r = statement.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
            r = -1;
        } finally {
            dataSource.closeConnection();
            return r;
        }
    }

    @Override
    public List<Map<String, Object>> queryTable(String sql, Object[] values) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        try {
            PreparedStatement statement = dataSource.createConnection().prepareStatement(sql);
            if (values != null) {
                for (int i = 1; i <= values.length; i++) {
                    statement.setObject(i, values[i - 1]);
                }
            }
            ResultSet resultSet = statement.executeQuery();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();
            while (resultSet.next()) {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    resultMap.put(resultSetMetaData.getColumnName(i), resultSet.getObject(i));
                }
                resultList.add(resultMap);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            dataSource.closeConnection();
            return resultList;
        }
    }
}
